package com.wang.designPattern.singleton;

import java.util.HashMap;
import java.util.Map;

/**
 * @description 容器式单例
 * @Author wangzilong
 * @Date 2025/1/6 8:34
 */
public class ContainerSingleton {
    // 单例容器
    private static final Map<String, Object> IOC = new HashMap<>();

    private ContainerSingleton() {
    }

    public static synchronized Object getInstance(String className) {
        // 容器中不存在该对象，则初始化创建
        if (!IOC.containsKey(className)) {
            Object obj = null;
            try {
                obj = Class.forName(className).newInstance();
                IOC.put(className, obj);
            } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                System.out.println("Load Singleton Object Failed :" + className);
            }
            return obj;
        }
        // 容器中存在该对象，则直接返回
        return IOC.get(className);
    }
}
